package com.uiao.stone;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 * MyWebMvcConfigureAdapter适配器放进来的请求才会在这继续拦截，即MyWebMvcConfigureAdapter先处理之后这个类再处理
 * MyWebMvcConfigureAdapter里的三个方法(静态资源，页面，适配器)里的适配器addInterceptors会添加这个拦截器
 * Created by Administrator on 2017/9/21.
 */
public class AuthInterceptor extends HandlerInterceptorAdapter implements HandlerInterceptor {

    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AuthInterceptor.class);

    /**
     * 这一步是在还没有进入controller的时候执行的
     * 如果返回值是true在执行完controller后会执行postHandle和afterCompletion，如果返回值是false就此结束
     *
     * @param request
     * @param response
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("preHandle 方法执行 ==>>");
        String url = request.getRequestURL().toString();
        String uri = request.getRequestURI();
        String ipAddress = request.getHeader("x-forwarded-for");
        String requestMethod = request.getMethod();
        //String clientPlatform = request.getHeader("ClientPlatform");

        logger.info("请求url :  " + url);
        logger.info("请求uri :  " + uri);
        // logger.info("请求地址 : " + ipAddress);
        logger.info("请求方法 : " + requestMethod);
        // logger.info(clientPlatform);

        /*String user = (String) request.getSession().getAttribute("username");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login/prelogin");
            logger.info("权限验证失败，请先登录");
            return false;
        } else {
            logger.info("权限验证成功");
            return true;
        }*/
        return true;
    }

    /**
     * 这一步是在controller已经处理完成，但是还没有返回model的时候处理的
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle 方法执行 ==>>");
    }

    /**
     * 这一步是在所有工作请求都已经结束，及前段都已经收到返回的结果时执行的
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("afterCompletion 方法执行 ==>>");
    }

}
